package com.realtyManage.springboot.Controller;

import com.alibaba.fastjson.JSON;
import com.realtyManage.springboot.Config.AliMessage;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Security;
import com.realtyManage.springboot.Model.Vo.ApplyEntity;
import com.realtyManage.springboot.Model.Vo.BaseEntity;
import com.realtyManage.springboot.Model.Vo.CouponEntity;
import com.realtyManage.springboot.Service.*;
import com.realtyManage.springboot.Utils.IdGen;
import com.realtyManage.springboot.Utils.SpringContextUtil;
import com.realtyManage.springboot.Utils.SysExecRsUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.realtyManage.springboot.Utils.CoreUtils.ajaxReturn;

/**
 * ApplyController
 * 报备
 * @Author 杭州素色网络科技有限公司
 * @Date 2019/12/24
 **/

@Controller
@RequestMapping("/")
public class ApplyController {
    @Autowired
    private CommodityService commodityService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IApplyInfoService applyInfoService;

    @Autowired
    private IUserTaskService userTaskService;

    @Autowired
    protected BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private ICustomerRegistrationService customerRegistrationService;

    @Autowired
    private ICustomerService customerService;
    /**
     * 新增报备
     * @param applyInfo
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addApplyInfo",method = RequestMethod.POST)
    private String addApplyInfo(ApplyInfo applyInfo, HttpServletRequest request){
        Integer code = -1;
        BaseEntity baseEntity =new BaseEntity();
        //拆分虚拟号
        String xPhone = applyInfo.getCustomerPhone().substring(0,3)+applyInfo.getCustomerPhone().substring(7,11);
        int userId = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId();
        //判断是否重复报备和是否已被人报备
        int num = applyInfoService.verification(userId,xPhone);   //0 正常操作  2 本人已经报备过  4 别人已经报备  8 已经存在客户
        if (num == 2){
            code = -5002;
            baseEntity.setInfoCode(code);
            baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
            return  JSON.toJSONString(baseEntity);
        }else if (num == 4){
            code = -5003;
            baseEntity.setInfoCode(code);
            baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
            return  JSON.toJSONString(baseEntity);
        }else if (num == 8){  //已存在客户
            code = -5004;
            baseEntity.setInfoCode(code);
            baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
            return  JSON.toJSONString(baseEntity);
        }
        applyInfo.setApplyTime(new Date());
        applyInfo.setState(0);
        applyInfo.setStep(0);
        applyInfo.setUserId(userId);
        applyInfo.setVirtualNumber(xPhone);
        applyInfo.setUserName(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getName().toString());
        if (applyInfoService.addApplyInfo(applyInfo) > 0){
            //发送短信通知
            String phones = applyInfo.getAcceptanceName();
            int begin=phones.indexOf("-") + 1;
            int last=phones.length();
            String phone = phones.substring(begin,last);
            String cPhone = applyInfo.getCustomerPhone().replace("****","****");
            String bPhone = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getTelephone();
            String rs = AliMessage.sendMessageBB(1, applyInfo.getAcceptanceName().substring(0,applyInfo.getAcceptanceName().indexOf("-")),phone,applyInfo.getUserName(),bPhone,applyInfo.getCustomerName(),cPhone,applyInfo.getDkTime(),applyInfo.getNum());    //接待人名称 报备人名称 报备人号码 客户名称 客户号码 带看时间 来访人数
            if (rs != null && rs.equals("OK")) {
                System.out.println("短信发送成功");
            } else {
                System.out.println("短信发送失败");
            }
            code = 1;
        }
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }


    /**
     * 查询报备规则
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryApplyRule",method = RequestMethod.GET)
    private String queryApplyRule(HttpServletRequest request) throws ParseException {
        return  JSON.toJSONString(applyInfoService.queryApplyRule());
    }


    /**
     * 修改规则
     * @param applyRule
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateApplyRule",method = RequestMethod.POST)
    private String updateApplyRule(ApplyRule applyRule,HttpServletRequest request) {
        Integer code = -1;
        BaseEntity baseEntity =new BaseEntity();
        if(applyInfoService.updateApplyRule(applyRule) > 0){
            code = 1;
        }
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }


    /**
     * 查询我的报备
     * @param applyEntity
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryApplyInfo",method = RequestMethod.GET)
    private String queryApplyInfo(ApplyEntity applyEntity, HttpServletRequest request) throws ParseException {
        applyEntity.setUserId(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        applyInfoService.queryApplyInfoS(applyEntity);
        return  JSON.toJSONString(applyInfoService.queryApplyInfoE(applyEntity));
    }


    /**
     * 置业顾扫码确定来访
     * @param applyEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/confirmVisit",method = RequestMethod.POST)
    private String confirmVisit(ApplyEntity applyEntity,HttpServletRequest request) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Integer code = -1;
        BaseEntity baseEntity =new BaseEntity();
        ApplyInfo ai = new ApplyInfo();
        ai.setId(applyEntity.getId());
        ai.setStep(1);
        ai.setAcceptanceId(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        ai.setAcceptanceName(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getName());
        //判断此码是否已经被扫过（虚拟号）
        ApplyInfo a = applyInfoService.queryApplyInfo(applyEntity.getVirtualNumber());
        if (a != null){
            if (a.getAcceptanceId() != null){
                code = -5007;
                baseEntity.setInfoCode(code);
                baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
                return  JSON.toJSONString(baseEntity);
            }
        }
        if(applyInfoService.confirmVisit(ai) > 0){
            //判断此用户是否已经入库
            if (customerRegistrationService.findVirtualNumber(applyEntity.getVirtualNumber()) > 0){
                code = -5008;
                baseEntity.setInfoCode(code);
                baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
                return  JSON.toJSONString(baseEntity);
            }
            //扫码自动进入客户信息表中
            CustomerRegistration customerRegistration = new CustomerRegistration();
            customerRegistration.setIsShow(0);
            customerRegistration.setEffective(0);
            customerRegistration.setIdentify(0);
            customerRegistration.setMoneyBack("0");
            customerRegistration.setTotalContract("0");
            customerRegistration.setLargeSum(0);
            customerRegistration.setDownPaymentsMoney("0");
            customerRegistration.setExpandCustomer(0);
            customerRegistration.setIncomingCall(0);
            customerRegistration.setInvitation(0);
            customerRegistration.setCustomerType("继续跟踪");
            customerRegistration.setVisit(1);
            customerRegistration.setIncomingCall(0);
            customerRegistration.setCustomerSource("渠道");
            customerRegistration.setReceptionId(ai.getAcceptanceId());
            customerRegistration.setReceptionName(ai.getAcceptanceName());
            customerRegistration.setComeTime(sdf.parse(sdf.format(new Date())));
            customerRegistration.setPhone(applyEntity.getCustomerPhone());
            customerRegistration.setName(applyEntity.getCustomerName());
            customerRegistration.setVirtualNumber(applyEntity.getVirtualNumber());
            customerRegistration.setSex(applyEntity.getSex());
            int cid = customerRegistrationService.saveCustomerRegistrationInfo(customerRegistration);
            if (cid > 0){
                //添加来访记录
                /*CustomerRecord customerRecord= new CustomerRecord();
                customerRecord.setCustomId(cid);
                customerRecord.setUid(ai.getAcceptanceId());
                customerRecord.setType(0);
                customerRecord.setInfoTime(new Date());
                customerRecord.setContent("无");
                if (customerService.addCustomerRecord(customerRecord) > 0){
                    code = 1;
                }*/
                code = 1;
            }
        }
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }


    /**
     * 置业顾问扫码记录
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/scanRecord",method = RequestMethod.GET)
    private String scanRecord(HttpServletRequest request) throws ParseException {
        Integer uid = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId();
        return  JSON.toJSONString(applyInfoService.scanRecord(uid));
    }


    /**
     * 设置是否为接待报备人员
     * @param user
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/staff",method = RequestMethod.POST)
    private String staff(User user,HttpServletRequest request) {
        Integer code = -1;
        BaseEntity baseEntity =new BaseEntity();
        if(userService.updateMyDetail(user) > 0){
            code = 1;
        }
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }

    /**
     * 查询接待报备人员
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryStaff",method = RequestMethod.GET)
    private String queryStaff(HttpServletRequest request) throws ParseException {
        return  JSON.toJSONString(userService.queryStaff());
    }


    /**
     * 报备详情
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryApplyDetailById",method = RequestMethod.GET)
    private String queryApplyDetailById(HttpServletRequest request) throws ParseException {
        String id = request.getParameter("id");
        return  JSON.toJSONString(applyInfoService.queryApplyDetailById(id));
    }

    /**
     * 查看全部报备信息
     * @param applyEntity
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/queryApplyInfoAll",method = RequestMethod.GET)
    private String queryApplyInfoAll(ApplyEntity applyEntity, HttpServletRequest request) throws ParseException {
        return  JSON.toJSONString(applyInfoService.queryApplyInfoAll(applyEntity));
    }


    /**
     * 删除无效报备
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteInvalidApply",method = RequestMethod.POST)
    private String deleteInvalidApply(HttpServletRequest request) {
        String id = request.getParameter("id");
        Integer code = -1;
        BaseEntity baseEntity =new BaseEntity();
        if(applyInfoService.deleteInvalidApply(id) > 0){
            code = 1;
        }
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }


    /**
     * 扫码进入经纪人身份
     * @param user
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insertAgent",method = RequestMethod.POST)
    private String insertAgent(User user, HttpServletRequest request, HttpServletResponse response) {
        BaseEntity baseEntity =new BaseEntity();
        Integer code = -1;
        if (userService.isExistPhone(user.getTelephone())){
            code = -101;
            baseEntity.setInfoCode(code);
            baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
            return  JSON.toJSONString(baseEntity);
        }
        user.setLevel(8); //经纪人
        user.setStatus(1);
        user.setIntegral(0);
        user.setPwd(bCryptPasswordEncoder.encode("000000"));
        user.setRegTime(new Date());
        user.setJoinTime(new Date());
        Integer uid = userService.insert(user).getId();
        if(uid > 0){
            user = userService.findById(uid);
            Security securityCfg = (Security) SpringContextUtil.getBean("security");
            Map<String, Object> claims = new HashMap<String, Object>();//创建payload的私有声明
            String[] roles = user.getLevel().toString().split(",");
            Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
            for(String role : roles)
            {
                authorities.add(new SimpleGrantedAuthority(role));
            }
            claims.put("uid", user.getId());
            claims.put("level",authorities);
            String token = Jwts.builder()
                    .setClaims(claims)//如果有私有声明，一定要先设置这个自己创建的私有的声明，这个是给builder的claim赋值，一旦写在标准的声明赋值之后，就是覆盖了标准的声明
                    //.setId(id)//设置jti(JWT ID)：是JWT的唯一标识，根据业务需要，这个可以设置为一个不重复的值，主要用来作为一次性token,从而回避重放攻击。
                    .setSubject(user.getTelephone())//主体
                    .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 365 * 1000))
                    .signWith(SignatureAlgorithm.HS512, securityCfg.getKey())
                    .compact();
            response.addHeader("Authorization", "Bearer " + token);
            return ajaxReturn(response, null, "扫码登录成功！", 1);
        }
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return  JSON.toJSONString(baseEntity);
    }

}
